package com.travel.server.manager.impl.dal;

import com.travel.common.exception.WorkCode;
import com.travel.common.exception.WorkException;
import com.travel.common.util.CollectionUtil;
import com.travel.server.manager.dao.TagInfoDao;
import com.travel.server.manager.model.TagInfo;
import com.travel.server.manager.model.TagInfoExample;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author: LiZhenhui
 * @Date: 2018/11/6 19:17
 * @Desc:
 */
@Component
@Slf4j
public class TagDal {

    @Autowired
    private TagInfoDao tagInfoDao;

    public PageDto<TagInfo> select(TagParam param){
        TagInfoExample example = makeExample(param);
        int total = tagInfoDao.countByExample(example);
        example.setOrderByClause("update_time desc");
        List<TagInfo> list = tagInfoDao.selectByExample(example);

        PageDto<TagInfo> pageDto = new PageDto<>();
        pageDto.setTotal(total);
        pageDto.setList(list);
        return pageDto;
    }

    public List<TagInfo> selectByExample(TagParam param){
        if(param == null){
            param = new TagParam();
        }
        TagInfoExample example = makeExample(param);
        return tagInfoDao.selectByExample(example);
    }

    public Integer insertOrUpdate(TagInfo tagInfo){
        if(tagInfo.getId() == null){
            tagInfoDao.insertSelective(tagInfo);
        }else{
            tagInfoDao.updateByPrimaryKey(tagInfo);
        }
        return tagInfo.getId();
    }

    public TagInfo selectById(Integer id){
        TagInfo tagInfo = tagInfoDao.selectByPrimaryKey(id);
        if(tagInfo == null){
            log.error("未查询到标签记录, id {}", id);
            throw new WorkException(WorkCode.RECORD_NOT_EXIST);
        }
        return tagInfo;
    }

    private TagInfoExample makeExample(TagParam param){
        TagInfoExample example = new TagInfoExample();
        TagInfoExample.Criteria criteria = example.or();
        if(StringUtils.isNotBlank(param.getName())){
            criteria.andNameEqualTo(param.getName());
        }
        if(!CollectionUtil.isEmpty(param.getIdList())){
            criteria.andIdIn(param.getIdList());
        }
        if(param.getState() != null){
            criteria.andStateEqualTo(param.getState());
        }
        if(param.getOffset() != null && param.getLimit() != null){
            example.setOffset(param.getOffset());
            example.setLimit(param.getLimit());
        }
        return example;
    }

    @Data
    public static class TagParam{
        private String name;

        private List<Integer> idList;

        private Integer state = 1;

        private Integer limit;

        private Integer offset;
    }
}
